import pygame
import random

# 初始化 Pygame
pygame.init()

# 定义常量
WIDTH = 800
HEIGHT = 600
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
PLAYER_SIZE = 30
ENEMY_SIZE = 30
SPEED = 5
ENEMY_SPEED = 3

# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("大逃杀游戏")

# 玩家类
class Player:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.speed = SPEED

    def move_up(self):
        if self.y > 0:
            self.y -= self.speed

    def move_down(self):
        if self.y < HEIGHT - PLAYER_SIZE:
            self.y += self.speed

    def move_left(self):
        if self.x > 0:
            self.x -= self.speed

    def move_right(self):
        if self.x < WIDTH - PLAYER_SIZE:
            self.x += self.speed

    def draw(self):
        pygame.draw.rect(screen, GREEN, (self.x, self.y, PLAYER_SIZE, PLAYER_SIZE))

# 敌人类
class Enemy:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.speed = ENEMY_SPEED

    def move_towards_player(self, player):
        dx = player.x - self.x
        dy = player.y - self.y
        distance = (dx ** 2 + dy ** 2) ** 0.5
        if distance > 0:
            self.x += self.speed * dx / distance
            self.y += self.speed * dy / distance

    def draw(self):
        pygame.draw.rect(screen, RED, (self.x, self.y, ENEMY_SIZE, ENEMY_SIZE))

# 创建玩家
player = Player(WIDTH // 2, HEIGHT // 2)

# 创建敌人列表
enemies = []
for _ in range(5):
    enemy_x = random.randint(0, WIDTH - ENEMY_SIZE)
    enemy_y = random.randint(0, HEIGHT - ENEMY_SIZE)
    enemy = Enemy(enemy_x, enemy_y)
    enemies.append(enemy)

# 游戏主循环
clock = pygame.time.Clock()
running = True
while running:
    screen.fill(BLACK)

    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                player.move_up()
            elif event.key == pygame.K_DOWN:
                player.move_down()
            elif event.key == pygame.K_LEFT:
                player.move_left()
            elif event.key == pygame.K_RIGHT:
                player.move_right()

    # 敌人移动
    for enemy in enemies[:]:
        enemy.move_towards_player(player)
        # 碰撞检测
        if (player.x < enemy.x + ENEMY_SIZE and
                player.x + PLAYER_SIZE > enemy.x and
                player.y < enemy.y + ENEMY_SIZE and
                player.y + PLAYER_SIZE > enemy.y):
            running = False

    # 绘制玩家和敌人
    player.draw()
    for enemy in enemies:
        enemy.draw()

    # 更新显示
    pygame.display.flip()
    clock.tick(60)

# 退出游戏
pygame.quit()